import os

import pytest

from storage.kvstore.plyvel import PlyvelKVStore


def test_get_put_plyvel(kv_path):
    store = PlyvelKVStore(kv_path)
    store.put(b'key', b'value')
    assert store.get(b'key') == b'value'


def test_getitem_setitem_plyvel(kv_path):
    store = PlyvelKVStore(kv_path)
    store[b'key'] = b'value'
    assert store[b'key'] == b'value'


def test_delete_plyvel(kv_path):
    store = PlyvelKVStore(kv_path)
    store.put(b'key', b'value')
    del store[b'key']
    assert store.get(b'key') is None


@pytest.mark.benchmark
def test_benchmark_read_plyvel(benchmark, kv_path, insert_keys, get_keys):
    db = PlyvelKVStore(str(kv_path))
    for k in insert_keys:
        db[k] = os.urandom(8)

    def benchmark_func():
        nonlocal db
        for k in get_keys:
            _ = db.get(k)

    benchmark(benchmark_func)


@pytest.mark.benchmark
def test_benchmark_write_plyvel(benchmark, kv_path, insert_keys):
    def benchmark_func():
        db = PlyvelKVStore(str(kv_path))
        for k in insert_keys:
            db[k] = os.urandom(8)

    benchmark(benchmark_func)
